package com.zz.yt.lib.bluetooth.base;


import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.whf.android.jar.util.storage.LattePreference;
import com.zz.yt.lib.ui.base.ui.LatteTitleDelegate;


import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * 蓝牙连接
 *
 * @author qf
 * @version 1.0
 **/
public abstract class BaseBluetoothDelegate extends LatteTitleDelegate {

    /**
     * 打开蓝牙
     */
    private static final int REQUEST_BT_CODE = 635;

    /**
     * 更换蓝牙连接
     */
    private static final int REQUEST_BT_REPLACE_CODE = 636;


    protected String mac = null;
    protected BluetoothAdapter mBluetooth = null;

    /*** 得到蓝牙设备句柄 */
    protected BluetoothDevice mDevice = null;

    /*** 用服务号得到socket */
    protected BluetoothSocket mSocket = null;

    /***  蓝牙是否成功  */
    protected boolean isPrint = false;


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initBluetooth();
    }

    /*******************蓝牙初始化******************/

    private void initBluetooth() {
        mBluetooth = BluetoothAdapter.getDefaultAdapter();
        if (mBluetooth == null) {
            ToastUtils.showShort("此设备不支持蓝牙");
            return;
        }
        if (!mBluetooth.isEnabled()) {
            LatteLogger.i("蓝牙没有打开");
            getSupportDelegate().startForResult(DeviceNoDelegate.create(), REQUEST_BT_CODE);
            return;
        }
        inMac();
    }

    /**
     * 是否连接
     */
    protected void inMac() {
        mac = LattePreference.getCustomAppProfile(Bluetooth.BLUETOOTH_ADDRESS);
        if (TextUtils.isEmpty(mac)) {
            //一次都没连接过
            getSupportDelegate().startForResult(ReplaceBleDelegate.create(), REQUEST_BT_REPLACE_CODE);
        } else {
            LatteLogger.i(mac);
            //连接该蓝牙
            inPermission();
        }
    }


    /***
     * 更换连接设备
     */
    protected void onReplace() {
        onStop();
        getSupportDelegate().startForResult(ReplaceBleDelegate.create(), REQUEST_BT_REPLACE_CODE);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_BT_CODE:
                    //未打开蓝牙直接返回时
                    if (mBluetooth != null && !mBluetooth.isEnabled()) {
                        getSupportDelegate().pop();
                    } else {
                        inMac();
                    }
                    break;
                case REQUEST_BT_REPLACE_CODE:
                    initBluetooth();
                    break;
                default:
                    break;
            }
        }
    }

    /*******************读取数据********************/
    protected void inPermission() {
        Observable
                .create((ObservableOnSubscribe<String>) emitter -> {
                    // 得到蓝牙设备句柄
                    mDevice = mBluetooth.getRemoteDevice(mac);
                    // 用服务号得到socket
                    if (mSocket == null) {
                        mSocket = mDevice.createRfcommSocketToServiceRecord(Bluetooth.UUID_SERVICE_CHANNEL);
                        //连接socket
                        try {
                            mSocket.connect();
                            emitter.onNext("连接" + mDevice.getName() + "成功！");
                            emitter.onComplete();
                            isPrint = true;
                        } catch (IOException e) {
                            try {
                                emitter.onNext("连接失败！");
                                mSocket.close();
                                mSocket = null;
                            } catch (IOException ee) {
                                emitter.onNext("关闭连接失败！");
                            }
                            isPrint = false;
                        }
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        hideLoading();
                        ToastUtils.showShort(s);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        hideLoading();
                        isPrint = false;
                        onNext("连接失败！");
                    }

                    @Override
                    public void onComplete() {
                        inRx();
                    }
                });
    }

    /**
     * 连接蓝牙成功
     */
    protected abstract void inRx();

    @Override
    public void onStop() {
        isPrint = false;
        super.onStop();
        try {
            if (mSocket != null) {
                mSocket.close();
                mSocket = null;
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    /**
     * 关闭电子秤连接
     */
    protected void disconnect() {
        isPrint = false;
        if (mSocket != null) {
            try {
                mSocket.close();
                mSocket = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (mSocket != null) {
            try {
                mSocket.close();
                mSocket = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
